package com.cn.qtms.common.jdbc;//类注释设置模板

import java.sql.*;

/**
 * @Name:DBUtil
 * @Description:
 * @Author: zhangyang
 * @Date: 2019-10-21 17:33
 **/
public class JdbcUtil {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    //静态代码块，在程序编译的时候执行
    static {
        try {
            //创建Properties对象
//            Properties p = new Properties();
//            //获取文件输入流
//            InputStream in = new FileInputStream("db.properties");
//            //加载输入流
//            p.load(in);
            //获取数据库连接驱动名字
            driver = "com.mysql.cj.jdbc.Driver";
            //获取数据库连接地址
            url ="jdbc:mysql://47.103.165.86:3306/soul?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=CONVERT_TO_NULL&failOverReadOnly=false&autoReconnect=true ";
            //获取数据库连接用户名
            username = "root";
            //获取数据库连接密码
            password = "Pass1234";
            if (driver != null && url != null
                    && username != null && password != null) {
                //加载驱动
                Class.forName(driver);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接对象
     *
     * @return Connection连接对象
     */
    public static Connection getConn() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }


    public static Connection getConn(String url,String username,String password){
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    /**
     * 关闭连接（Connection连接对象必须在最后关闭）
     *
     * @param conn Connection连接对象
     * @param st   编译执行对象
     * @param rs   结果集
     */
    public static void close(Connection conn, Statement st, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
